/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-06-20
 * Time: 0:09
 */
//力扣：https://leetcode.cn/problems/kth-node-from-end-of-list-lcci/submissions/637901302/
//实现一种算法，找出单向链表中倒数第 k 个节点。返回该节点的值。//
class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }
public class Test {
    public static int kthToLast(ListNode head, int k) {
        ListNode p1=head;
        ListNode p2=head;
        while(k!=0){
            p2=p2.next;
            k--;
        }
        while(p2!=null){
            p1=p1.next;
            p2=p2.next;
        }
        return p1.val;
    }

    public static void main(String[] args) {
        ListNode list5 = new ListNode(5, null);
        ListNode list4 = new ListNode(4, list5);
        ListNode list3 = new ListNode(3, list4);
        ListNode list2 = new ListNode(2, list3);
        ListNode list1 = new ListNode(1, list2);
        System.out.println(kthToLast(list1, 3));
    }
}
